import React, { Component } from 'react'
import './form.scss'
import PropTypes from 'prop-types';
export default class Form extends Component {
  constructor (props) {
    super(props)
    this.state = {
      itemList: []
    }
    this.addItem = this.addItem.bind(this)
    this.getFormData = this.getFormData.bind(this)
    this.validate = this.validate.bind(this)
  }
  getChildContext () {
    return {
      Form: this
    }
  }
  getFormData () {
    return this.props.formData || null
  }
  validate () {
    let isPassAll = true
    this.state.itemList.forEach(u => {
      const isPassItem = u.validate()
      if (!isPassItem) {
        isPassAll = false
      }
    })
    return new Promise((resolve, reject) => {
      if (isPassAll) {
        resolve()
      } else {
        reject()
      }
    })
  }
  resetValidate () {
    this.state.itemList.forEach(u => {
      u.resetValidate()
    })
  }
  addItem (formItem) {
    this.state.itemList.push(formItem)
  }
  render () {
    return (
      <div className="tbcForm">
        { this.props.children }
      </div>
    )
  }
}

Form.childContextTypes = {
  Form: PropTypes.any
}